import { createRouter, createWebHistory } from 'vue-router'

import { constantRoutes } from './constantRoutes'
import { routes } from './routes'

const modules = import.meta.glob('@/views/**/*.vue')

const routeFormat = (data = []) => {
  data.forEach(item => {
    delete item.id
    delete item.title

    if (item.children) {
      routeFormat(item.children)
    } else {
      const componentPath = `/src/views${item.path}/index.vue`
      if (modules[componentPath]) {
        item.component = modules[componentPath]
      } else {
        console.warn(`Component not found: ${componentPath}`)
      }
    }
  })
}

const newRoutes = JSON.parse(JSON.stringify(routes))
routeFormat(newRoutes)

export const appRoutes = [
  {
    path: '/',
    redirect: '/userInfo'
  },
  {
    path: '/layout',
    component: () => import('@/layout/index.vue'),
    children: newRoutes
  },
  ...constantRoutes
]

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_APP_BASE_URL),
  routes: appRoutes
})

export default router
